/**
 * @Title: DatbRecordSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月21日 上午9:54:27
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import java.util.List;

import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.utils.StringUtils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android_serialport_api.FingerprintManager;
import android_serialport_api.FingerprintReader;
import android_serialport_api.FingerprintReader.OnDownCharListener;
import android_serialport_api.FingerprintReader.OnStoreCharListener;

import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.beans.RecordResp;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CodecUtils;

/**
 * @ClassName: DatbRecordSyncLogic
 * @Description: 同步矫正人员的信息
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月21日 上午9:54:27
 */
public class DatbRecordSyncLogic extends Logic {

	private static final String TAG = "DatbRecordSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack;// 是否有回调，此需要Handle
	private int mCurrentIndex = 1;// 当前页
	private int mCount;
	private Message mMessage;

	private FingerprintReader mAsyncFingerprint;
	private int mFingerId = 0;
	private int mFingerCount = 0;
	private int mFingerCurrent = -1;
	private List<FingerPrintBean> mFingerPrintBeans;

	public DatbRecordSyncLogic() {

	}

	public DatbRecordSyncLogic(AppContext appContext, Handler handler) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
	}

	public DatbRecordSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
	}

	@Override
	public void execute() {
		Log.i(TAG, "-----run time ---001-->" + System.currentTimeMillis());
		initAsyncFingerprint();
		try {
			//mKjdb.deleteTable("table_record");
			//mKjdb.deleteByWhere(RecordBean.class, null);
			mKjdb.deleteTable(RecordBean.class);
		} catch (Exception e) {
		}
		Log.i(TAG, "-----run time ---002-->" + System.currentTimeMillis());
		datbRecordSync();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}

	}

	private void initAsyncFingerprint() {
		Log.i(TAG, "-----run time ---003-->" + System.currentTimeMillis());
		mAsyncFingerprint = FingerprintManager.getInstance().getNewAsyncFingerprint();
		mAsyncFingerprint.PS_Empty();
		mFingerId = 0;
		if (mAsyncFingerprint == null) return;
		mAsyncFingerprint.setOnDownCharListener(new OnDownCharListener() {

			@Override
			public void onDownCharSuccess() {
				Log.i(TAG, "setOnDownCharListener onDownCharSuccess mFingerId:"
						+ mFingerId);
				mAsyncFingerprint.PS_StoreChar(2, mFingerId);
			}

			@Override
			public void onDownCharFail() {
				Log.i(TAG, "setOnDownCharListener onDownCharFail mFingerId:"
						+ mFingerId);
				storeFinger();
			}
		});
		mAsyncFingerprint.setOnStoreCharListener(new OnStoreCharListener() {

			@Override
			public void onStoreCharSuccess() {
				Log.i(TAG,
						"setOnStoreCharListener onStoreCharSuccess mFingerId:"
								+ mFingerId);
				storeFinger();
			}

			@Override
			public void onStoreCharFail() {
				Log.i(TAG, "setOnStoreCharListener onStoreCharFail mFingerId:"
						+ mFingerId);
				storeFinger();
			}
		});
		Log.i(TAG, "-----run time ---004-->" + System.currentTimeMillis());
	}

	// 档案同步
	private void datbRecordSync() {
		Log.i(TAG, "-----run time ---005-->" + System.currentTimeMillis());
		mParams = new KJFileParams();
		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
		mParams.put(AppGlobal.HTTP_PARAM_CURRENTINDEX,
				String.valueOf(mCurrentIndex));
		mParams.put(AppGlobal.HTTP_PARAM_ORGANID, mMachId);
		String url = HttpConfig.POST_URL_DATB_RECORDSYNC;
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->mCurrentIndex:" + mCurrentIndex);
		KJHttp kjHttp = new KJHttp();
		Log.i(TAG, "-----run time ---006-->" + System.currentTimeMillis());
		kjHttp.post(url, mParams, new HttpCallBack() {

			@Override
			public void onSuccess(Object arg0) {
				Log.i(TAG, "-----run time ---007-->" + System.currentTimeMillis());
				String result = CodecUtils.base64Decode(arg0.toString());
				Log.i(TAG, "-----run time ---008-->" + System.currentTimeMillis());
				Log.i(TAG, "----->Result:" + result);
				RecordResp recordResp = new GsonBuilder().create().fromJson(
						result, RecordResp.class);
				Log.i(TAG, "-----run time ---009-->" + System.currentTimeMillis());
				// 存入数据库
				if (recordResp != null && !recordResp.isEmpty()) {
					Log.i(TAG, "-----run time ---010-->" + System.currentTimeMillis());
					Log.i(TAG, "----->organResp:" + recordResp.toString());
					List<RecordBean> beans = recordResp.getValues();
					try {
						for (RecordBean recordBean : beans) {
							if (recordBean != null) {
								String userId = recordBean.getElectronicsId();
								String userName = recordBean.getName();
								String fp1 = recordBean.getFp_1();
								String fp2 = recordBean.getFp_2();
								String cardNo = recordBean.getCardNO();
								if (StringUtils.isEmpty(fp1)
										&& StringUtils.isEmpty(fp2)) {
									recordBean.setIsEntry(0);
								} else {
									recordBean.setIsEntry(1);
								}
								Log.i(TAG, "--------->recordBean:" + recordBean);
								mKjdb.save(recordBean);
								// 保存工作人员指纹信息
								// 如果存在更新数据，如果不存在添加
								Log.i(TAG, "-----run time ---011-->" + System.currentTimeMillis());
								addOrUpdateFingerPrintInfo(new FingerPrintBean(userId,
										userName, fp1,cardNo, 1, 1));
								Log.i(TAG, "-----run time ---012-->" + System.currentTimeMillis());
								addOrUpdateFingerPrintInfo(new FingerPrintBean(userId,
										userName, fp2,cardNo, 1, 2));
								mCount++;
							}
						}
						if (!recordResp.isLastPage()) {
							mCurrentIndex++;
							datbRecordSync();
						} else {
							Log.i(TAG, "-----run time ---013-->" + System.currentTimeMillis());
							saveFinger();
						}
					} catch (Exception e) {
						mMessage.arg1 = 1;
						send();
					}
				} else {
					mMessage.arg1 = 2;
					send();
				}
			}

			@Override
			public void onLoading(long arg0, long arg1) {
				Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:" + arg1);
				mMessage.arg1 = 3;
				send();
			}

			@Override
			public void onFailure(Throwable arg0, int arg1, String arg2) {
				Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:" + arg2);
				mMessage.arg1 = 3;
				send();
			}
		});
	}

	private void addOrUpdateFingerPrintInfo(FingerPrintBean bean) {
		if (bean != null) {
			try {
				List<FingerPrintBean> beans = mKjdb.findAllByWhere(FingerPrintBean.class,
						"userId = '" + bean.getUserId()
								+ "' and type = 1 and state = " + bean.getState());
				if (beans != null && !beans.isEmpty()) {
					FingerPrintBean b = beans.get(0);
					bean.setId(b.getId());
					mKjdb.update(bean);
				}else {
					mKjdb.save(bean);
				}
			} catch (Exception e) {
			}
		}
	}

	// 储存指纹信息到设备
	private synchronized void storeFinger() {
		if (mAsyncFingerprint != null) {
			mFingerCurrent++;
			FingerPrintBean bean = null;
			if (mFingerCurrent > -1 && mFingerCurrent < mFingerCount) {
				bean = mFingerPrintBeans.get(mFingerCurrent);
				if (bean != null && !StringUtils.isEmpty(bean.getFp())) {
					mFingerId = bean.getId();
					byte[] b = CodecUtils
							.base64DecodeToByte(bean.getFp());
					if (b != null) {
						Log.i(TAG, "-----run time ---015-->" + System.currentTimeMillis());
						mAsyncFingerprint.PS_DownChar(b);
					}else {
						storeFinger();
					}
				} else {
					storeFinger();
				}
			} else {
				// 通知
				mMessage.arg1 = 0;
				mMessage.arg2 = mCount;
				send();
			}
		} else {
			// 通知
			mMessage.arg1 = 0;
			mMessage.arg2 = mCount;
			send();
		}
	}

	private void saveFinger() {
		try {
			mFingerId = 0;
			mFingerCount = 0;
			mFingerCurrent = -1;
			mFingerPrintBeans = mKjdb.findAll(FingerPrintBean.class);
		} catch (Exception e) {
			mMessage.arg1 = 0;
			mMessage.arg2 = mCount;
			send();
		}

		if (mFingerPrintBeans != null && !mFingerPrintBeans.isEmpty()) {
			mFingerCount = mFingerPrintBeans.size();
			Log.i(TAG, "-----run time ---014-->" + System.currentTimeMillis());
			storeFinger();
		}else {
			mMessage.arg1 = 0;
			mMessage.arg2 = mCount;
			send();
		}
	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
